package com.chatplus.application.controller.api.extend;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chatplus.application.common.constant.RedisPrefix;
import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.dto.extend.WeiBoHotDto;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.redisson.codec.SerializationCodec;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Comparator;
import java.util.List;

/**
 * 获取微博相关信息
 */
@Validated
@RestController
@RequestMapping("/api/extend/")
@Tag(name = "微博第三方API", description = "微博第三方API")
public class WeiBoExtendController {
    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(WeiBoExtendController.class);

    private final RedissonClient redissonClient;

    public WeiBoExtendController(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }

    @GetMapping("/weiboHot")
    @Operation(summary = "获取微博热搜")
    public List<WeiBoHotDto> weiboHot() {
        String redisKey = RedisPrefix.EXTEND_REDIS_PREFIX_TEST + "weiboHot";
        RBucket<List<WeiBoHotDto>> rBucket = redissonClient.getBucket(redisKey, new SerializationCodec());
        List<WeiBoHotDto> cache = rBucket.isExists() ? rBucket.get() : null;
        if (CollectionUtils.isNotEmpty(cache)) {
            return cache;
        }
        LOGGER.message("获取微博热搜").info();
        String url = "https://weibo.com/ajax/side/hotSearch";
        try (HttpResponse response = HttpUtil.createGet(url).execute()) {
            String dataText = response.body();
            JSONObject responseMap = JSONUtil.parseObj(dataText);
            JSONObject data = responseMap.getJSONObject("data");
            JSONArray realtime = data.getJSONArray("realtime");
            List<WeiBoHotDto> weiBoHotDtoList = realtime.stream().map(hot -> {
                JSONObject hotData = (JSONObject) hot;
                WeiBoHotDto weiBoHot = new WeiBoHotDto();
                weiBoHot.setCategory(hotData.getStr("category"));
                weiBoHot.setNote(hotData.getStr("note"));
                weiBoHot.setNum(hotData.getLong("num", 0L));
                weiBoHot.setUrl(URLEncoder.encode("https://s.weibo.com/weibo?q=%23" + (hotData.getStr("note") + "%23"), StandardCharsets.UTF_8));
                return weiBoHot;
            }).toList();
            cache = weiBoHotDtoList.stream()
                    .sorted(Comparator.comparingLong(WeiBoHotDto::getNum).reversed())
                    .limit(15)
                    .toList();
            rBucket.set(cache, Duration.ofMinutes(10));
        } catch (Exception e) {
            LOGGER.message("获取微博热搜失败").exception(e).error();
        }
        return cache;
    }
}
